//
//  LLWebViewController.m
//  LLWebViewController
//
//  Created by liushaohua on 2017/1/19.
//  Copyright © 2017年 liushaohua. All rights reserved.
//

#import "LLWebViewController.h"
#import <WebKit/WebKit.h>
#import <AVFoundation/AVFoundation.h>
#import "UIDevice+TFDevice.h"
#import "CCZSpreadButton.h"
#import "EDWalletCenterViewController.h"
#import "EDPTGameDetailViewController.h"
static NSString * identiy_callback  = @"identiy_callback";
//#define NAVI_HEIGHT  64
@interface LLWebViewController ()<UIWebViewDelegate,WKNavigationDelegate,WKUIDelegate,UIGestureRecognizerDelegate,WKScriptMessageHandler>
@property (nonatomic, strong) WKWebView *wk_WebView;
@property (nonatomic, strong) CCZSpreadButton *com;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) UIBarButtonItem *backBarButtonItem;
@property (nonatomic, strong) UIBarButtonItem *closeBarButtonItem;
@property (nonatomic, strong) id <UIGestureRecognizerDelegate>delegate;
@property (nonatomic, strong) UIRefreshControl *refreshControl;
@property (nonatomic, strong) UIProgressView *loadingProgressView;
@property (nonatomic, strong) UIButton *reloadButton;
@property (nonatomic, strong) UIButton *blakButton;
@end

@implementation LLWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = _titleStr;
  
    if ([_titleStr isEqualToString:@"存款"] ||[_titleStr isEqualToString:@"帮我存款"])
    {
         self.navigationItem.rightBarButtonItem = [UIBarButtonItem RightitemWithImageNamed:@"" title:@"我已付款" target:self action:@selector(subimt)];
    }
    [self createWebView];
    [self createNaviItem];
    [self loadRequest];
    if (_isType== 3)
    {
        //允许转成横屏
        [self allowRotation:YES];
    }
}
- (void)subimt
{
    if (self.isWebGo ==YES) {
        [self.navigationController.viewControllers enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSLog(@"%zi %@", idx, obj);
            UIViewController *controller = (UIViewController *)obj;
            if ([controller isKindOfClass:[LLWebViewController class]]) {
                
                LLWebViewController *vc = (LLWebViewController *)controller;
                if (vc.isType !=1 || vc.isShowGame ==YES) {
                    [self.navigationController popToViewController:vc animated:YES];
                    *stop = YES;
                }
            }
            if ([controller isKindOfClass:[EDPTGameDetailViewController class]]) {
                EDPTGameDetailViewController *vc = (EDPTGameDetailViewController *)controller;
                [self.navigationController popToViewController:vc animated:YES];
                *stop = YES;
            }
        }];
        
    }else{
          [self.navigationController popToRootViewControllerAnimated:YES];
    }
  
}

//横屏竖屏
- (void)allowRotation:(BOOL)allowRotation
{
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotation = allowRotation;
    if (allowRotation) {
        //调用转屏代码
        [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight];
      
        _wk_WebView.frame = CGRectMake(0, 0, UIScreenWidth, UIScreenHeight);
        _loadingProgressView.frame = CGRectMake(0, 0, UIScreenWidth, 2);
//         _blakButton.frame = CGRectMake(0, 0, 46, 100);
    }else
    {
        [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
        _wk_WebView.frame = CGRectMake(0, 0, UIScreenWidth, UIScreenHeight);
        _loadingProgressView.frame = CGRectMake(0, 0, UIScreenWidth, 2);
//         _blakButton.frame = CGRectMake(0, 0, 46, 100);
    }
    
    if (self.isType !=1 || self.isShowGame ==YES) {
        self.com.frame = CGRectMake(UIScreenWidth-100, UIScreenHeight-100, 50, 50);
    }
    
}
#pragma mark 版本适配
- (void)createWebView {
//    self.automaticallyAdjustsScrollViewInsets = NO;
//    [self.view addSubview:self.reloadButton];
    if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 8.0) {
        [self.view addSubview:self.wk_WebView];
        [self.view addSubview:self.loadingProgressView];
      
    } else {
        [self.view addSubview:self.webView];
    }
    
    
    if (self.isType !=1 || self.isShowGame ==YES) {
        CCZSpreadButton *com  = [[CCZSpreadButton alloc] initWithFrame:CGRectMake(kScreenWidth-100, kScreenHeight-100, 50, 50)];
        com.itemsNum = 4;
        com.autoAdjustToFitSubItemsPosition = YES;
        com.spreadButtonOpenViscousity = NO;
        com.wannaToScaleSpreadButtonEffect = NO;
        com.backgroundColor = [UIColor clearColor];
        //com.radius
        com.normalImage = [UIImage imageNamed:@"menu_Open"];
        com.selImage = [UIImage imageNamed:@"menu_Close"];
        com.images = @[@"menu_back",@"menu_Refush",@"menu_cunkuan",@"menu_Zhuan"];
        [com spreadButtonDidClickItemAtIndex:^(NSUInteger index) {
            NSLog(@"%ld",index);
            switch (index) {
                case 0:
                {
                    [self back:nil];
                }
                    break;
                case 1:
                {
                    NSHTTPCookie*cookie;
                    NSHTTPCookieStorage*storage =[NSHTTPCookieStorage sharedHTTPCookieStorage];for(cookie in[storage cookies]){      [storage deleteCookie:cookie];}
                    [self loadRequest];
                }
                    break;
                case 2:
                {
                    EDWalletCenterViewController *vc2 = [[EDWalletCenterViewController alloc] init];
                    if (self.isType== 3) {
                        AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                        appDelegate.allowRotation = NO;//关闭横屏仅允许竖屏
                        [self allowRotation:NO];
                    }
                    vc2.title = @"钱包";
                    vc2.selectIndex =0;
                    [AppDelegate shareAppdelegate].index = 0;
                    vc2.isWebGo = YES;
                    [self.navigationController pushViewController:vc2 animated:YES];
                }
                    break;
                case 3:
                {
                    EDWalletCenterViewController *vc2 = [[EDWalletCenterViewController alloc] init];
                    if (self.isType== 3) {
                        AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                        appDelegate.allowRotation = NO;//关闭横屏仅允许竖屏
                        [self allowRotation:NO];
                    }
                    vc2.title = @"钱包";
                    vc2.isWebGo = YES;
                    vc2.selectIndex =1;
                    [AppDelegate shareAppdelegate].index = 1;
                    [self.navigationController pushViewController:vc2 animated:YES];
                }
                    break;
                    
                default:
                    break;
            }
        }];
        self.com = com;
        
        [self.view addSubview:self.com];
        
    }
  
    
    
}

- (UIWebView*)webView {
    if (!_webView) {
        _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
        _webView.delegate = self;
        if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 10.0 && _isPullRefresh) {
            _webView.scrollView.refreshControl = self.refreshControl;
        }
    }
    return _webView;
}


- (WKWebView*)wk_WebView {
    if (!_wk_WebView) {
        
        // js配置
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        [userContentController addScriptMessageHandler:self name:identiy_callback];
        
        // WKWebView的配置
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.userContentController = userContentController;
        config.preferences = [[WKPreferences alloc]init];
      
        _wk_WebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, (_isType== 1)?kStatusBarAndNavigationBarHeight:0, UIScreenWidth, (_isType== 1)?kScreenHeight-kStatusBarAndNavigationBarHeight:kScreenHeight ) configuration:config];
        _wk_WebView.navigationDelegate = self;
        _wk_WebView.backgroundColor = CLEARCOLOR;
        _wk_WebView.UIDelegate = self;
        
       
        if (@available(iOS 11.0, *)){
             _wk_WebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        //添加此属性可触发侧滑返回上一网页与下一网页操作
        _wk_WebView.allowsBackForwardNavigationGestures = YES;
      
        //下拉刷新
        if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 10.0 && _isPullRefresh) {
            _wk_WebView.scrollView.refreshControl = _refreshControl;
        }
        
        //进度监听
        [_wk_WebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    }
    return _wk_WebView;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        _loadingProgressView.progress = [change[@"new"] floatValue];
        if (_loadingProgressView.progress == 1.0) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self->_loadingProgressView.hidden = YES;
            });
        }
    }
}

- (void)dealloc {
    [_wk_WebView removeObserver:self forKeyPath:@"estimatedProgress"];
    [_wk_WebView stopLoading];
    [_webView stopLoading];
    _wk_WebView.UIDelegate = nil;
    _wk_WebView.navigationDelegate = nil;
    _webView.delegate = nil;
//    [_wk_WebView.configuration.userContentController removeScriptMessageHandlerForName:identiy_callback];
}


- (UIProgressView*)loadingProgressView {
    if (!_loadingProgressView) {
        _loadingProgressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, (_isType== 1)?kStatusBarAndNavigationBarHeight:0 , self.view.bounds.size.width, 2)];
        _loadingProgressView.progressTintColor = TABTITLECOLOR;
        _loadingProgressView.backgroundColor = CLEARCOLOR;
    }
    return _loadingProgressView;
}

- (UIRefreshControl*)refreshControl {
    if (!_refreshControl) {
        _refreshControl = [[UIRefreshControl alloc]init];
        [_refreshControl addTarget:self action:@selector(webViewReload) forControlEvents:UIControlEventValueChanged];
    }
    return _refreshControl;
}

- (void)webViewReload {
    [_webView reload];
    [_wk_WebView reload];
}

- (UIButton*)reloadButton {
    if (!_reloadButton) {
        _reloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _reloadButton.frame = CGRectMake(0, 0, 150, 150);
        _reloadButton.center = self.view.center;
        _reloadButton.layer.cornerRadius = 75.0;
        [_reloadButton setBackgroundImage:[UIImage imageNamed:@"placeholder"] forState:UIControlStateNormal];
       [_reloadButton setTitle:@"无效地址" forState:UIControlStateNormal];
        
        [_reloadButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [_reloadButton setTitleEdgeInsets:UIEdgeInsetsMake(200, -50, 0, -50)];
        _reloadButton.titleLabel.numberOfLines = 0;
        _reloadButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        CGRect rect = _reloadButton.frame;
        rect.origin.y -= 100;
        _reloadButton.frame = rect;
        _reloadButton.enabled = NO;
    }
    return _reloadButton;
}
- (void)createNaviItem {
    [self showLeftBarButtonItem];
}

- (void)showLeftBarButtonItem {
    if ([_webView canGoBack] || [_wk_WebView canGoBack]) {
        [self.view addSubview:self.blakButton];
    } else {

      
        
        
    }
}
- (void)back:(UIButton*)item {
    if ([_webView canGoBack] || [_wk_WebView canGoBack]) {
        [_webView goBack];
        [_wk_WebView goBack];
    } else {
        //允许转成横屏
        [self allowRotation:NO];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark 自定义导航按钮支持侧滑手势处理
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_isType== 1) {
        [self.navigationController setNavigationBarHidden:NO animated:NO]; //设置隐藏
    }else
    {
       //  [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
        [self.navigationController setNavigationBarHidden:YES animated:NO]; //设置隐藏
    }
    
    if (self.navigationController.viewControllers.count > 1) {
        self.delegate = self.navigationController.interactivePopGestureRecognizer.delegate;
        self.navigationController.interactivePopGestureRecognizer.delegate = self;

    }
    
    if (_isType== 3) {
        AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        appDelegate.allowRotation = YES;//关闭横屏仅允许竖屏
        //允许转成横屏
        [self allowRotation:YES];
    }
    
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [self allowRotation:NO];
   // [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    [self.navigationController setNavigationBarHidden:NO animated:NO]; //设置隐藏
    self.navigationController.interactivePopGestureRecognizer.delegate = self.delegate;
    // self.navigationController.navigationBar.frame = CGRectMake(0, -44, kScreenWidth, 44);//矫正导航栏移位
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    return self.navigationController.viewControllers.count > 1;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return self.navigationController.viewControllers.count > 1;
}
#pragma mark 加载请求
- (void)loadRequest {
   
    if (![self.urlStr hasPrefix:@"http"]) {//是否具有http前缀
        self.urlStr = [NSString stringWithFormat:@"http://%@",self.urlStr];
    }
    if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 8.0) {
        [_wk_WebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];
    } else {
        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];
    }
}

#pragma mark WebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
//        [self showLoadingAnimation];
//    NSString *requestString = [[[request URL] absoluteString]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSLog(@"requestString : %@",requestString);
    webView.hidden = NO;
    // 不加载空白网址
    if ([request.URL.scheme isEqual:@"about"]) {
        webView.hidden = NO;
        return NO;
    }

    return YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    //导航栏配置
    self.navigationItem.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    [self showLeftBarButtonItem];
    [_refreshControl endRefreshing];
//    [self stopLoadingAnimation];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    webView.hidden = YES;
}

#pragma mark WKNavigationDelegate

#pragma mark 加载状态回调

//页面开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
    webView.hidden = NO;
    _loadingProgressView.hidden = NO;
//     [self showLoadingAnimation];
    if ([webView.URL.scheme isEqual:@"about"]) {
        webView.hidden = YES;
    }
}
//JS调用OC
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    NSString * body = message.body;
//    if ([body isEqualToString:@"onSuccess"]) {
//
//        SuccessViewController * SuccessVC = [[SuccessViewController alloc] init];
//        SuccessVC.title = @"认证失败";
//        [self.navigationController pushViewController:SuccessVC animated:YES];
//
//    }else if ([body isEqualToString:@"onFailure"])
//    {
//        FailViewController * failVC = [[FailViewController alloc] init];
//        failVC.title = @"认证失败";
//        [self.navigationController pushViewController:failVC animated:YES];
//    }
    
}
//页面加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    //导航栏配置
    [webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable title, NSError * _Nullable error) {
        self.navigationItem.title = title;
    }];
 
    
    [self stopLoadingAnimation];
    [self showLeftBarButtonItem];
    
    [_refreshControl endRefreshing];
}

-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSString *urlStr = navigationAction.request.URL.absoluteString;
    if ([urlStr hasPrefix:@"alipays://"] || [urlStr hasPrefix:@"alipay://"]) {
        NSURL* alipayURL = [self changeURLSchemeStr:urlStr];
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:alipayURL options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO} completionHandler:^(BOOL success) {
                
            }];
        } else {
            // Fallback on earlier versions
            [[UIApplication sharedApplication] openURL:alipayURL];
        }
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
-(NSURL*)changeURLSchemeStr:(NSString*)urlStr{
    NSString* tmpUrlStr = urlStr.copy;
    if([urlStr containsString:@"fromAppUrlScheme"]) {
        tmpUrlStr = [tmpUrlStr stringByRemovingPercentEncoding];
        NSDictionary* tmpDic = [self dictionaryWithUrlString:tmpUrlStr];
        NSString* tmpValue = [tmpDic valueForKey:@"fromAppUrlScheme"];
        tmpUrlStr = [[tmpUrlStr stringByReplacingOccurrencesOfString:tmpValue withString:@"你对应的URLSchemes"] mutableCopy];
        tmpUrlStr = [[tmpUrlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] mutableCopy];
    }
    NSURL * newURl = [NSURL URLWithString:tmpUrlStr];
    return newURl;
}
-(NSDictionary*)dictionaryWithUrlString:(NSString*)urlStr{
    if(urlStr && urlStr.length&& [urlStr rangeOfString:@"?"].length==1) {
        NSArray *array = [urlStr componentsSeparatedByString:@"?"];
        if(array && array.count==2) {
            NSString*paramsStr = array[1];
            if(paramsStr.length) {
                NSString* paramterStr = [paramsStr stringByRemovingPercentEncoding];
                NSData *jsonData = [paramterStr dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
                return responseDic;
            }
        }
    }
    return nil;
}
//页面加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    webView.hidden = YES;
}

////HTTPS认证
//- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
////    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
////        if ([challenge previousFailureCount] == 0) {
////            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
////            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
////        } else {
////            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
////        }
////    } else {
////        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
////    }
//    // 判断服务器采用的验证方法
//    if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
//        // 如果没有错误的情况下 创建一个凭证，并使用证书
//        if (challenge.previousFailureCount == 0) {
//            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
//            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
//        }else {
//            // 验证失败，取消本次验证
//            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
//        }
//    }else {
//        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
//        
//    }
//    
//}




@end
